package edu.uclmgmu.bacteriosec.aspects.sis;

import java.io.InputStream;

import edu.uclmgmu.bacteriosec.aspects.common.Store;

privileged aspect SIS_IMInverter {
	private InputStream input;

	java.io.InputStream around(java.net.Socket f) : target(f) && call(java.io.InputStream java.net.Socket.getInputStream()) {
		System.out.println(thisJoinPointStaticPart.getSignature());
		InputStream auxi=proceed(f);
		if (auxi instanceof java.net.SocketInputStream) {
			this.input=auxi;
			System.out.println("Capturado");
		}
		return proceed(f);
	}

	after(java.io.InputStream f, byte[] b, int off, int len) : target(f) && args(b, off, len) && call(int InputStream.read(byte[], int, int)) {
		if (this.input!=null) {
			int numberOfCurrentCall=Store.get(thisJoinPointStaticPart.getSignature());
			int numberOfCallInTurn=Store.getNumberOfCallInTurn();
			if (numberOfCurrentCall==numberOfCallInTurn) {
				System.out.println("<" + new String(b) + ">");
				Store.log(this.getClass().getCanonicalName(), numberOfCurrentCall, thisJoinPointStaticPart.getSignature());
				byte[] theArray=new byte[b.length];
				int cont=0;
				for (int i=b.length-1; i>=0; i--) {
					theArray[cont++]=b[i];
				}
				b=theArray;
				System.out.println("changed to: <" + new String(b) + ">");
			} 
			Store.put(thisJoinPointStaticPart.getSignature(), ++numberOfCurrentCall);
		}
	}

	/*	 int around(java.io.InputStream f, byte[] b, int off, int len) : target(f) && args(b, off, len) && call(int read(byte[], int, int)) {
		 System.out.println(thisJoinPointStaticPart.getSignature());
		 if (this.input!=null) {
			int counter=Store.get(thisJoinPointStaticPart.getSignature());
			System.out.println(thisJoinPointStaticPart.getSignature() + "-> " + counter);
			Store.put(thisJoinPointStaticPart.getSignature(), ++counter);
			if (counter==1) {
				System.out.println("<" + new String(b) + ">");
				byte[] theArray=new byte[b.length];
				int cont=0;
				for (int i=b.length-1; i>=0; i--) {
					theArray[cont++]=b[i];
				}
				b=theArray;
				System.out.println("<" + new String(b) + ">");
			} 
		 }
		 return proceed(f, b, off, len);
	 }*/

	/*		after() : target(java.net.SocketInputStream) && args() && call(* java.net.SocketInputStream.*()) {
				int counter=Store.get(thisJoinPointStaticPart.getSignature());
				System.out.println(thisJoinPointStaticPart.getSignature() + "-> " + counter);
		}

		after(java.net.SocketInputStream f, byte[] b) : target(f) && args(b) && call(public int java.net.SocketInputStream.read(byte[])) {
			if (f instanceof java.net.SocketInputStream) {
				int counter=Store.get(thisJoinPointStaticPart.getSignature());
				System.out.println(thisJoinPointStaticPart.getSignature() + "-> " + counter);
			} else {
				System.out.println("No");
			}
		}
	 */}
